package 分治;

/**
 * @description:
 * @author: ywk
 * @date: 2021-03-13
 */
public class 吃香蕉 {
    //输入：piles=[3,6,7,11],H=8,H为耗费时间只内
    //输出：4 ,说明最小次香蕉的速度
    public static int minEatingSpeed(int[] piles, int H) {
        int max = getMax(piles), min = 1;
        while (min <= max) {
            int mid = min + (max - min) / 2;
            if (canFinish(piles, mid, H)) {
                max = mid - 1;
            } else {
                min = mid + 1;
            }
        }
        return min;
    }

    private static boolean canFinish(int[] piles, int speed, int h) {
        int time = 0;
        for (int pile : piles) {
            time += pile / speed + (pile % speed == 0 ? 0 : 1);
        }
        return h >= time;
    }    //堆中最大的元素

    private static int getMax(int[] piles) {
        int max = piles[0];
        for (int pile : piles) {
            max = pile > max ? pile : max;
        }
        return max;
    }

    public static void main(String[] args) {
        System.out.println(minEatingSpeed(new int[]{3, 6, 7, 11}, 4));
    }
}
